/*
 * Systemprogrammierung
 * Multiplayer-Quiz
 *
 * Client
 *
 * listener.c: Implementierung des Listener-Threads
 */

#define NULL 0 //NULL
#include "listener.h"
#include "gui/gui_interface.h"
#include "common/rfc.h"
#include "common/sockets.h"
#include "common/util.h"
#include <linux/stddef.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "common/question.h"
#include "stdbool.h"
#include <stdio.h>
#include <unistd.h> //optind sollte da drin sein
#include <stdint.h> //uint8_t sollte eig kein Fehler mehr sein
#include <stddef.h> //NULL sollte kein Fehler mehr sein

#include "command.h"
#include <sys/types.h> //
#include <getopt.h>
#include <pthread.h>
#include <netdb.h>
#include "common/util.h"


#define MAX_NAME_LENGTH (32)
#define MAX_PLAYER (6)

//Prototypen
void SetPlayerData(struct NET_MESSAGE* msg);
void DrawPlayerList (struct ST_GLOBAL_CLIENT_INFO* clientInfo);

struct ST_PLAYER_DATA
{
	char name [MAX_NAME_LENGTH];
	uint8_t id;
};

struct ST_PLAYER_DATA players [MAX_PLAYER];

//Listener Thread starten
void *listener_thread(void *data)
{
	debugPrint("Listener Thread gestartet.");

	struct ST_GLOBAL_CLIENT_INFO* clientInfo = (struct ST_GLOBAL_CLIENT_INFO*) data;

	//Login Schleife
	while (clientInfo->sock != 0)
	{
		//Nachricht empfangen
		struct NET_MESSAGE recvdata;
		recvdata.header.type = 0;

		//Fehler beim empfangen
		if(ReceiveRFCMsg(clientInfo->sock, &recvdata)<0)
		{
			debugPrint("Listener Thread wird beendet. Fehler beim empfangen");
			guiShowErrorDialog("Listener Thread wird beendet. Fehler beim empfangen", 1);
			return(NULL);
		}

		//RFC Nachricht richtig empfangen
		else
		{
			//Auf Headertypen switchen
			switch(recvdata.header.type)
			{
			case TYPE_IS_LOGIN_RESPONSE_OK:
				debugPrint("Login ist OK");
				break;

			case TYPE_IS_PLAYER_LIST:
				SetPlayerData(&recvdata);
				DrawPlayerList(clientInfo);
				break;
			}

		}

		SecureFree (recvdata.data);
		recvdata.data = NULL;
	}

	//Beende Thread
	pthread_exit(NULL);
	return(NULL);
}


int AddCatalog(char* data, uint16_t len)
{
	if (len > 0)
	{
		// allokiere Speicher fÃ¼r nullterminierten String
		char* catalogName = (char*) Uint8Malloc(len + 1);
		memmove(catalogName, data, len);

		// call GUI Funktion
		preparation_addCatalog(catalogName);

		// Speicher Freigeben
		SecureFree(catalogName);
		catalogName = NULL;
	}

	return 0;
}


